<template>
  <div class="home-container">
    <el-header class="home-header">
      <div class="header-content">
        <div class="header-left">
          <img src="@/assets/logo.svg" alt="Logo" class="logo">
          <h1 class="title">查看所有用户信息</h1>
        </div>
        <div class="header-right">
          <el-button type="danger" @click="logout" size="large">退出登录</el-button>
        </div>
      </div>
    </el-header>

    <el-main class="home-main">
      <el-card class="stats-card">
        <div class="stats-container">
          <div class="stat-item">
            <div class="stat-number">{{ users.length }}</div>
            <div class="stat-label">总用户数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ activeUsers }}</div>
            <div class="stat-label">活跃用户</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ inactiveUsers }}</div>
            <div class="stat-label">未活跃用户</div>
          </div>
        </div>
      </el-card>

      <el-card class="user-list-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">所有用户信息</span>
            <div style="display: flex; gap: 10px;">
              <el-button type="primary" @click="refreshUsers">刷新数据</el-button>
              <el-button type="success" @click="showAddUserDialog">添加用户</el-button>
            </div>
          </div>
        </template>

        <el-table :data="users" stripe style="width: 100%" border>
          <el-table-column prop="userId" label="用户ID" width="120" align="center" sortable />
          <el-table-column prop="username" label="用户名" width="140" align="center" sortable />
          <el-table-column prop="nickname" label="昵称" width="140" align="center" sortable />
          <el-table-column prop="email" label="邮箱" width="220" align="center" />
          <el-table-column prop="phone" label="电话" width="160" align="center" />
          <el-table-column prop="isActive" label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.isActive" type="success" effect="dark">激活</el-tag>
              <el-tag v-else type="warning" effect="dark">未激活</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="操作" width="160" align="center">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="showDeleteConfirm(row.userId)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加用户对话框 -->
      <el-dialog
        v-model="addUserDialogVisible"
        title="添加用户"
        width="500px"
        :before-close="handleAddUserDialogClose"
      >
        <el-form ref="addUserFormRef" :model="addUserForm" :rules="addUserRules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" placeholder="请输入用户名" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password" placeholder="请输入密码" autocomplete="off" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="addUserForm.confirmPassword" type="password" placeholder="请确认密码" autocomplete="off" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="addUserForm.nickname" placeholder="请输入昵称" autocomplete="off" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addUserForm.phone" placeholder="请输入电话" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" placeholder="请输入邮箱" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleAddUserDialogClose">取消</el-button>
            <el-button type="primary" @click="handleAddUser">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const users = ref([])
const loading = ref(false)
const error = ref('')

// 计算属性：活跃用户数
const activeUsers = computed(() => {
  return users.value.filter(user => user.isActive).length
})

// 计算属性：未活跃用户数
const inactiveUsers = computed(() => {
  return users.value.filter(user => !user.isActive).length
})

// 获取所有用户信息
const fetchUsers = async () => {
  try {
    loading.value = true
    error.value = ''
    const response = await axios.get('/users') // 假设后端提供/users接口
    users.value = response.data.data || []
  } catch (err) {
    error.value = '获取用户列表失败，请稍后重试'
    console.error('获取用户列表错误:', err)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取用户数据
onMounted(() => {
  fetchUsers()
})

// 刷新用户列表
const refreshUsers = () => {
  fetchUsers()
}

// 显示删除确认对话框
const showDeleteConfirm = async (userId) => {
  try {
    console.log('准备删除的用户ID:', userId) // 确认ID是否正确
    await ElMessageBox.confirm(
      '确定要删除该用户吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteUser(userId)
    ElMessage.success('用户删除成功')
    refreshUsers()
  } catch (error) {
    // 取消操作时，error.name 为 'CanceledError'
    if (error.name !== 'CanceledError') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// 添加用户对话框状态
const addUserDialogVisible = ref(false)

// 添加用户表单数据
const addUserForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  phone: '',
  email: ''
})

// 表单引用
const addUserFormRef = ref(null)

// 添加用户表单验证规则
const addUserRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== addUserForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
})

// 显示添加用户对话框
const showAddUserDialog = () => {
  addUserDialogVisible.value = true
}

// 关闭添加用户对话框
const handleAddUserDialogClose = () => {
  addUserDialogVisible.value = false
  resetAddUserForm()
}

// 重置添加用户表单
const resetAddUserForm = () => {
  addUserFormRef.value?.resetFields()
}

// 处理添加用户
const handleAddUser = async () => {
  try {
    // 验证表单
    await addUserFormRef.value.validate()

    // 准备请求数据
    const requestData = {
      username: addUserForm.username,
      password: addUserForm.password,
      nickname: addUserForm.nickname,
      phone: addUserForm.phone,
      email: addUserForm.email
    }

    // 发送请求
    const res = await axios.post('/register', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('用户添加成功')
      addUserDialogVisible.value = false
      resetAddUserForm()
      refreshUsers() // 刷新用户列表
    } else {
      ElMessage.error(res.data.msg || '添加用户失败')
    }
  } catch (err) {
    console.error('添加用户错误:', err)
    // 处理后端返回的重复注册错误
    if (err.response?.status === 409 || err.response?.data?.msg?.includes('重复') || err.response?.data?.msg?.includes('存在')) {
      ElMessage.error('用户名或邮箱已被使用')
    } else if (err.name !== 'CanceledError') {
      ElMessage.error('添加用户失败，请检查网络连接或稍后重试')
    }
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    console.log('尝试删除用户ID:', userId) // 确认传入的userId正确
    const response = await axios.delete(`/users/${userId}`)
    console.log('删除接口返回:', response.data) // 查看完整返回数据
    if (response.data.code !== 200) {
      throw new Error(response.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除用户错误详情:', {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message
    })
    throw error
  }
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  router.push('/')
}
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.home-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 40px;
  height: 80px;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.title {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
}

.home-main {
  padding: 40px;
  flex: 1;
  overflow: auto;
}

.stats-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-container {
  display: flex;
  gap: 40px;
  padding: 20px 0;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 36px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 18px;
  color: #909399;
}

.user-list-card {
  margin-top: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.card-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-table td {
  padding: 16px;
}

.el-tag {
  font-size: 14px;
  font-weight: 500;
}
</style>